package com.devicemantra.coordinate.operations;
import java.io.IOException;

import javax.naming.spi.StateFactory;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.devicemantra.coordinate.exceptions.dataobjects.CDatabaseException;
import com.devicemantra.coordinate.exceptions.jaxb.CJAXBException;
import com.devicemantra.coordinate.exceptions.operations.CReadPayloadException;
import com.devicemantra.coordinate.exceptions.operations.CStateAlreadyExistsException;
import com.devicemantra.coordinate.exceptions.operations.CWritePayloadException;
import com.devicemantra.coordinate.interfaces.http.CHttpReader;
import com.devicemantra.coordinate.interfaces.http.CHttpWriter;
import com.devicemantra.coordinate.jaxb.JAXBRequestFactory;
import com.devicemantra.coordinate.jaxb.JAXBResponseFactory;
import com.devicemantra.coordinate.jaxb.ObjectFactory;
import com.devicemantra.coordinate.jaxb.Request;
import com.devicemantra.coordinate.jaxb.Response;
import com.devicemantra.coordinate.jaxb.ResponseData;
import com.devicemantra.coordinate.jaxb.Status;
import com.devicemantra.coordinate.dataobjects.*;

@SuppressWarnings("serial")
public class CopyOfAddState extends HttpServlet 
{
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException 
	{
		String lXmlInputStr = null;
		/* Read the Content of the HTTP request as a String representation */
		try {
			lXmlInputStr = CHttpReader.getAsString(req);
		} catch(CReadPayloadException lException) {
			
		}
		Request lRequest = null;	
		try {
			lRequest = JAXBRequestFactory.parseRequest(lXmlInputStr);
		} catch (CJAXBException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		System.out.println("State name " + lRequest.getCRequestData().getCState().getName());
		System.out.println("State capital " + lRequest.getCRequestData().getCState().getCapital());
		
		int lRespCode = 200;
		String lResponseStr = "Success adding State ";
		
		try {
			CStateFactory.createNewState(lRequest.getCRequestData().getCState().getName());
		} catch (CDatabaseException e2) {
			lRespCode = 500;
			lResponseStr = "Error persisting to Database";
		} catch (CStateAlreadyExistsException e2) {
			lRespCode = 500;
			lResponseStr = "State with that name already exists";
		}
		
		String lXmlResponseStr = null;
		try {
			lXmlResponseStr = JAXBResponseFactory.createStatusResponse(lRespCode,lResponseStr);
		} catch (CJAXBException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		CHttpWriter.setContentType("text/xml");
		try {
			CHttpWriter.writeAsString(resp, lXmlResponseStr);
		} catch (CWritePayloadException e) {
			System.out.println("ERROR: Caught Exception " + e.getMessage());
		}
	}
}
